//
//  ViewController.m
//  sqlTool
//
//  Created by iMac on 16/11/2.
//  Copyright © 2016年 com.iszt.dev.ios. All rights reserved.
//

#import "ViewController.h"
#import "FMDB.h"
#import "storyListObj.h"
#import "storyObj.h"

#define DB_SongDat @"HorrorStoreList"

@interface ViewController()<NSTextViewDelegate>

@property (unsafe_unretained) IBOutlet NSTextView *contentTextView;
@property (weak) IBOutlet NSPopUpButton *storyListPopUpBtn;
@property (weak) IBOutlet NSTextField *storyIdTextField;
@property (weak) IBOutlet NSTextField *typeTextField;
@property (weak) IBOutlet NSTextField *countryTextField;
@property (weak) IBOutlet NSTextField *nameTextField;
@property (weak) IBOutlet NSTextField *desTextField;
@property (weak) IBOutlet NSButton *addBtn;
@property (unsafe_unretained) IBOutlet NSTextView *logTextView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // Do any additional setup after loading the view.
    
    _contentTextView.delegate = self;
    [self createTable];
    [self updatePopUpList];
}

- (IBAction)btn1Event:(id)sender {
    NSLog(@"btn1");
    
    if (!_storyListPopUpBtn.selectedItem) {
        return;
    }
    
    NSMutableArray *tmpMutableArray = [NSMutableArray new];
    NSString *tmpStr = [_contentTextView.textStorage string];
    NSArray *tmpArray = [tmpStr componentsSeparatedByString:@"\n"];
    for (NSString *str in tmpArray) {
        if (str.length != 0) {
            if ([str rangeOfString:@"http"].location != NSNotFound) {
                storyObj *obj = [storyObj new];
                obj.type = 0;
                obj.content = str;
                [tmpMutableArray addObject:obj];
            }else{
                storyObj *obj = [storyObj new];
                obj.type = 1;
                obj.content = str;
                [tmpMutableArray addObject:obj];
            }
        }
    }
    
    [self addContent:[tmpMutableArray copy]];
}

- (IBAction)btn2Event:(id)sender {
    NSString *tmpStr = [_contentTextView.textStorage string];
    NSLog(@"%@",tmpStr);
}

- (IBAction)btn3Event:(id)sender {
    if (_storyIdTextField.stringValue.length == 0) {
        return;
    }
    if (_typeTextField.stringValue.length == 0) {
        _typeTextField.stringValue = [NSString stringWithFormat:@"0"];
    }
    if (_countryTextField.stringValue.length == 0) {
        _countryTextField.stringValue = [NSString stringWithFormat:@"0"];
    }
    if (_nameTextField.stringValue.length == 0) {
        return;
    }
    if (_desTextField.stringValue.length == 0) {
        return;
    }
    storyListObj *obj = [storyListObj new];
    obj.story_id = [[_storyIdTextField stringValue]integerValue];
    obj.type = [[_typeTextField stringValue]integerValue];
    obj.country = [[_countryTextField stringValue]integerValue];
    obj.name = [NSString stringWithFormat:@"%@",[_nameTextField stringValue]];
    obj.des = [NSString stringWithFormat:@"%@",[_desTextField stringValue]];
    [self addStory:obj];
    [self updatePopUpList];
}


- (void)updatePopUpList{
    [_storyListPopUpBtn removeAllItems];
    NSArray *tmpArray = [self List];
    for (storyListObj *obj in tmpArray) {
        [_storyListPopUpBtn addItemWithTitle:obj.name];
    }
    if (_storyListPopUpBtn.itemArray.count) {
        [_storyListPopUpBtn selectItemAtIndex:(_storyListPopUpBtn.itemArray.count - 1)];
    }
    
    storyListObj *lastObj = [tmpArray lastObject];
    _storyIdTextField.stringValue = [NSString stringWithFormat:@"%ld",lastObj.story_id + 1];
    _typeTextField.stringValue = [NSString stringWithFormat:@"0"];
    _countryTextField.stringValue = [NSString stringWithFormat:@"0"];
}

#pragma mark - TextView Delegate
// Set this class to be the delegate of the UITextView. Now when a user will paste a text in that textview, this delegate will be called.
- (BOOL)textView:(NSTextView *)textView shouldChangeTextInRange:(NSRange)affectedCharRange replacementString:(NSString *)replacementString{
    if ([replacementString isEqualToString:[[NSPasteboard generalPasteboard] stringForType:NSPasteboardTypeString]]) {
        NSLog(@"replacementString:%@",replacementString);
        NSAttributedString *tmpStr = [[NSAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@\n",replacementString]];
        [[textView textStorage] appendAttributedString:tmpStr];
        return NO;
    }
    return YES;
}


#pragma mark - Public Method
- (void)createTable{
    
    NSFileManager * fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:[self dbPath:DB_SongDat]] == NO) {
        // create it
        FMDatabase * db = [FMDatabase databaseWithPath:[self dbPath:DB_SongDat]];
        if ([db open]) {
            
            NSString * sql;
            BOOL res;
            
            //创建歌单数据库
            sql = @"CREATE TABLE 'storieslist' ('story_id' INTEGER, country INTEGER, type INTEGER, name TEXT, des TEXT)";
            res = [db executeUpdate:sql];
            if (!res) {
                NSLog(@"error when creating db table");
            } else {
                NSLog(@"succ to creating db table");
            }
            
            //创建歌曲数据库
            sql = @"CREATE TABLE 'story' ('story_id' INTEGER, type INTEGER, content TEXT, other TEXT)";
            res = [db executeUpdate:sql];
            if (!res) {
                NSLog(@"error when creating db table");
            } else {
                NSLog(@"succ to creating db table");
            }
            
            [db close];
        } else {
            NSLog(@"error when open db");
        }
    }
}

- (BOOL)addStory:(storyListObj *)storyList
{
    FMDatabase * db = [FMDatabase databaseWithPath:[self dbPath:DB_SongDat]];
    if ([db open]) {
        BOOL res = NO;
        
        //插入歌单
        res = [db executeUpdate:@"INSERT INTO 'storieslist' ('story_id', 'country', 'type', 'name', 'des') VALUES (?,?,?,?,?)",
               [NSNumber numberWithInteger:storyList.story_id], [NSNumber numberWithInteger:storyList.country], [NSNumber numberWithInteger:storyList.type], storyList.name, storyList.des];
        
        
        [db close];
    }
    NSAttributedString *tmpStr = [[NSAttributedString alloc]initWithString:[NSString stringWithFormat:@"Add storiesList(story_id:%ld, country:%ld, type:%ld, name:%@, des:%@) Success!\n",storyList.story_id, storyList.country, storyList.type, storyList.name, storyList.des]];
    [[_logTextView textStorage] appendAttributedString:tmpStr];
    [_logTextView scrollRangeToVisible:NSMakeRange(_logTextView.string.length, 0)];
    return true;
}

- (BOOL)addContent:(NSArray *)storyArray
{
    int textCount = 0;
    int imageCount = 0;
    NSArray *tmpArray = [self List];
    
    storyListObj *obb = [tmpArray objectAtIndex:_storyListPopUpBtn.indexOfSelectedItem];
    NSInteger story_id = obb.story_id;
    
    FMDatabase * db = [FMDatabase databaseWithPath:[self dbPath:DB_SongDat]];
    if ([db open]) {
        BOOL res = NO;
        
        for (storyObj *story in storyArray) {
            //插入
            res = [db executeUpdate:@"INSERT INTO 'story' ('story_id', 'type', 'content', 'other') VALUES (?,?,?,?)",
                   [NSNumber numberWithInteger:story_id], [NSNumber numberWithInteger:story.type], story.content, story.other];
            if (story.type == 0) {
                imageCount++;
            }else{
                textCount++;
            }
        }

        
        [db close];
    }
    
    NSAttributedString *tmpStr = [[NSAttributedString alloc]initWithString:[NSString stringWithFormat:@"Add story content(textCount:%d, imageCount:%d) Success!\n",textCount, imageCount]];
    [[_logTextView textStorage] appendAttributedString:tmpStr];
    [_logTextView scrollRangeToVisible:NSMakeRange(_logTextView.string.length, 0)];
    
    return true;
}

#pragma mark - Setter/Getter
-(NSString *)dbPath:(NSString *)dbName{
    NSString *dataPath = [NSString stringWithFormat:@"%@/Documents",NSHomeDirectory()];
    dataPath = [dataPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.db",dbName]];
    return dataPath;
}

-(NSArray *)List{
    NSMutableArray *storyList = [NSMutableArray new];
    
    FMDatabase * db = [FMDatabase databaseWithPath:[self dbPath:DB_SongDat]];
    
    if ([db open]) {
        FMResultSet * rs = [db executeQuery:[NSString stringWithFormat:@"SELECT * From 'storieslist' order by story_id"]];
        while ([rs next]) {
            storyListObj *obj = [storyListObj new];
            obj.story_id = [rs intForColumn:@"story_id"];
            obj.country = [rs intForColumn:@"country"];
            obj.type = [rs intForColumn:@"type"];
            obj.name = [NSString stringWithFormat:@"%@",[rs stringForColumn:@"name"]];
            obj.des = [NSString stringWithFormat:@"%@",[rs stringForColumn:@"des"]];
            
            
            [storyList addObject:obj];
        }
        
        [db close];
    }
    
    return [storyList copy];
}

- (void)setRepresentedObject:(id)representedObject {
    [super setRepresentedObject:representedObject];

    // Update the view, if already loaded.
}


@end
